#!/bin/bash

######################### SupTime Project v0.7 #############################
# This bash script generates png image with system top and current uptime. #
############################################################################
# Dear User - consider that this script has been written FOR PERSONAL USE  #
# by a programming newbie - please don't await anything amazing from it!   #
############################################################################
# Script requires:                                                         #
# - ImageMagick >= 6.2.5                                                   #
# - uptimed                                                                #
# - uprecords (uprecords-cgi)                                              #
# - ncftp                                                                  #
# - scp                                                                    #
############################################################################
# Contact? >> sufixx[at]gmail.com                                          #
############################################################################

# Please edit settings below and comment this line:
echo "[1;31m[e][0m [1;29mConfigure your script first![0m"; exit;

# Configurable variables
BASE_DIR=`pwd`			# It is higly recommended to put here normal, obsolete path!
OUT=$BASE_DIR/out.png		# Path to output image.
THEME="theme_gimpuj"		# Theme dir name which will be used.
#CHECKS=0			# Uncomment to disable software checks permamently

# Upload settings
UPLOAD="none"			# Choose method of image upload: ftp/scp/none
USER="user"			# ftp/scp username
PASSWORD="password"		# ftp/scp password (sorry, no safe-md5 variable support yet)
HOST="ftp.com"			# ftp host
FTP_PORT=21			# ftp port
SSH_PORT=22			# scp port
FTP_DIR="public_html/"		# ftp directory
SSH_DIR="~/"			# scp directory

# Binaries locations - if you get errors like "convert not found", uncomment lines and put here real locations of  binaries.
# You can search for them with command whereis (ex. `whereis uprecords`)
UPRECORDS_BIN=`whereis -b uprecords | awk '{print $2}'`
IDENTIFY_BIN=`whereis -b identify | awk '{print $2}'`
SCP_BIN=`whereis -b scp | awk '{print $2}'`
NCFTPPUT_BIN=`whereis -b ncftpput | awk '{print $2}'`
CONVERT_BIN=`whereis -b convert | awk '{print $2}'`
COMPOSITE_BIN=`whereis -b composite | awk '{print $2}'`

# No need to change
VERSION="0.7"
TMP_DIR=/tmp
BACKGROUND=$BASE_DIR/$THEME/bg.png
FOREGROUND=$BASE_DIR/$THEME/fg.png

# Colors in output messages
w="[0m"
W="[0m[1;29m"
y="[0m[0;33m"
Y="[0m[1;33m"
G="[0m[1;32m"
R="[0m[1;31m"

# Script command-line parameters
case "$1" in
	-h)
		echo -e "$G[i]$W Available options are:$w
 $Y-h$w	Show this help
 $Y-i$w	Print information about settings
 $Y-n$w	Turn off software checks
 $Y-s$w	Generate shutdown image
 $Y-v$w	Print script version\n
$Y[!]$W Due to bash limitations You cannot use more than one option at once.$w"
		exit;
		;;
	-n)
		CHECKS=0
		echo "$Y[!]$W Running without software checks.$w"
		;;
	-v)
		echo "$G[i]$W SupTime script version: $VERSION$w"
		exit;
		;;
	-i)
		echo -e "$G[i]$W Information about settings:$w
$y Temporary directory:$w	$TMP_DIR
$y Base directory:$w		$BASE_DIR
$y Output file location:$w	$OUT
$y Image theme:$w		$THEME
$y Upload method:$w		$UPLOAD
$y Upload user:$w		$USER
$y Upload host:$w		$HOST
\n$G[i]$W Binaries locations:$w
$y 	uprecords$w	$UPRECORDS_BIN
$y 	identify$w	$IDENTIFY_BIN
$y 	scp$w		$SCP_BIN
$y 	ncftpput$w	$NCFTPPUT_BIN
$y 	convert$w		$CONVERT_BIN
$y 	composite$w	$COMPOSITE_BIN"
		exit;
		;;
esac

# Network connection checker
connection_check () {
	ping -c 1 google.com > /dev/null && NET=1 || NET=0
}

# Check network connection if uploading via ftp or ssh
case "$UPLOAD" in
	ftp|ssh|scp)
		echo "$G[i]$W Checking network connection.$w"
		connection_check
		if [ "$NET" != "1" ]; then
			echo "$R[e]$W No network connection!$w"
			exit;
		fi
		;;
esac

# Software checks
if [ "$CHECKS" != "0" ]; then
	# Check if uprecords is installed
	if [ ! -e "$UPRECORDS_BIN" ]; then
		echo "$R[e]$W Please install uprecords program.$w"
		exit;
	fi
	# Check if ImageMagick is installed
	IMAGEMAGICK_VER=`$IDENTIFY_BIN -version | head -n 1 | awk {'print $3'} \
	| sed 's/\.//g'`
	if [ "$IMAGEMAGICK_VER" -lt "625" ]; then
		echo "$R[e]$W Your ImageMagick version is older than$w $Y6.2.5$w"
		exit;
	fi
fi

# Read current uptime from uprecords
if [ "$1" == "-s" ]; then
	PID=`ps aux | grep suptimed.sh | grep "su -c" | head -n 1 | awk '{print $2}'`
	UPTIME="shutdown"
	if [ -n "$PID" ]; then
		kill $PID > /dev/null&& \
		echo "$G[i]$W Rendering shutdown image.$w"
	else
		echo "$Y[!]$W No SupTimeDaemon running found!$w"
		echo "$G[i]$W Rendering shutdown image.$w"
	fi
else
	echo "$G[i]$w Rendering uptime image"
	UPTIME_DAYS=`$UPRECORDS_BIN -a | grep "\->" | awk '{print $3}'`
	case "$UPTIME_DAYS" in
		1)
			UPTIME=`$UPRECORDS_BIN -a | grep "\->" | awk '{print $3 $4 $5 $6 }' \
			| sed 's/\day/ day/' |sed 's/\,/ /'`
			;;
		*)
			UPTIME=`$UPRECORDS_BIN -a | grep "\->" | awk '{print $3 $4 $5 }' \
			| sed 's/\days/ days/' |sed 's/\,/ /'`
			;;
	esac
fi

# Read top uptime from uprecords
TOP_DAYS=`$UPRECORDS_BIN -a | head -n 3 | tail -n 1 | sed 's/\->//' | awk '{print $2}'`
case $TOP_DAYS in
	1)
		TOP=`$UPRECORDS_BIN -a | head -n 3 | tail -n 1 | sed 's/\->//' \
		| awk '{print $2 $3 $4 $5}' | sed 's/\day/ day/' |sed 's/\,/ /'`
		;;
	*)
		TOP=`$UPRECORDS_BIN -a | head -n 3 | tail -n 1 | sed 's/\->//' \
		| awk '{print $2 $3 $4}' | sed 's/\days/ days/' |sed 's/\,/ /'`
		;;
esac

# Load theme configuration and text layer
if [ -e $BASE_DIR/$THEME/theme.conf ]; then
	THEME_LINES=`cat $BASE_DIR/$THEME/theme.conf  |wc -l`
	if [ "$THEME_LINES" -ge 5 ]; then
		cat $BASE_DIR/$THEME/theme.conf | head -n 3 > $TMP_DIR/theme.tmp
		cat $BASE_DIR/$THEME/theme.conf | grep "#FONT#" | sed 's/\#FONT# //' \
		>> $TMP_DIR/theme.tmp
		. $TMP_DIR/theme.tmp
		LAYERS_LOADED=0
		while [ "$LAYERS_LOADED" -lt  "$LAYERS" ]; do
			LAYERS_LOADED=$[$LAYERS_LOADED+1]
			cat $BASE_DIR/$THEME/theme.conf | grep "#LAYER$LAYERS_LOADED#" \
			> $TMP_DIR/LAYER"$LAYERS_LOADED".tmp
			LAYERS_LINES=`cat $TMP_DIR/LAYER*.tmp| wc -l`
			if [ "$LAYERS_LINES" -ge 2 ]; then
				. $TMP_DIR/LAYER"$LAYERS_LOADED".tmp
			else
				echo "$R[e]$W Error in theme config file![0"
				exit;
			fi
		done
	else
		echo "$R[e]$W Error in theme config file![0"
		exit;
	fi
else
	echo "$R[e]$W Theme not found! Check if it really exists.[0"
	exit;
fi

# Render image with text from text file
cat $TMP_DIR/up1.txt | $CONVERT_BIN -background transparent -pointsize $FONT_SIZE \
-fill $FONT_COLOR -font $BASE_DIR/$THEME/$FONT label:@- -append $TMP_DIR/text1.png
LAYERS_MADE=0
while [ "$LAYERS_MADE" -lt "$LAYERS" ]; do
	LAYERS_MADE=$[$LAYERS_MADE+1]
	cat $TMP_DIR/up"$LAYERS_MADE".txt | $CONVERT_BIN -background transparent \
	-pointsize $FONT_SIZE -fill $FONT_COLOR -font $BASE_DIR/$THEME/$FONT \
	label:@- -append $TMP_DIR/text"$LAYERS_MADE".png
done

# Merge graphical background, text image and foreground
cat $BASE_DIR/$THEME/theme.conf | grep "#COMPOSITE#" > $TMP_DIR/composite.tmp
. $TMP_DIR/composite.tmp

# Show size of generated image
KBYTES=`du -kh $OUT | awk {'print $1'}`
echo "$G[i]$W Rendered image size is$w$Y $KBYTES$w"

# Cleanup
rm -f $TMP_DIR/composite* $TMP_DIR/up*.txt $TMP_DIR/text*.png $TMP_DIR/theme*.tmp \
$TMP_DIR/extra*.tmp $TMP_DIR/LAYER*.tmp

# Upload image
case "$UPLOAD" in
	ssh|scp)
		$SCP_BIN	 -P $SSH_PORT $OUT $USER@$HOST:$SSH_DIR/ && \
		echo " $G[i]$W Image uploaded via scp.$w"
		;;
	ftp)
		$NCFTPPUT_BIN -u $USER -p $PASSWORD -P $FTP_PORT $HOST $FTP_DIR $OUT > /dev/null && \
		echo " $G[i]$W Image uploaded via ftp.$w"
		;;
esac


# Delete image from hard disk if uploaded to remote server
case "$UPLOAD" in
	ftp|ssh|scp)
		rm -f $OUT
		;;
esac

exit;
